 
package com.zdkj.subway.stm.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.constant.StmTableCommon;
import com.zdkj.subway.stm.dto.in.SwStInputPassengerWorkDTO;
import com.zdkj.subway.stm.entity.SwStInputPassengerWork;
import com.zdkj.subway.stm.entity.SwStInputPassengerWorkFree;
import com.zdkj.subway.stm.entity.SwStmStationDataEntryLog;
import com.zdkj.subway.stm.mapper.SwStInputPassengerWorkFreeMapper;
import com.zdkj.subway.stm.mapper.SwStInputPassengerWorkMapper;
import com.zdkj.subway.stm.service.SwStInputPassengerWorkFreeService;
import com.zdkj.subway.stm.service.SwStmStationDataEntryLogService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.zdkj.subway.stm.util.BeanUtilsStm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 乘客事务录入明细表【免费出站票发售】
 *
 * @author cuilei
 * @date 2020-05-25 13:37:47
 */
@Service
@AllArgsConstructor
public class SwStInputPassengerWorkFreeServiceImpl extends ServiceImpl<SwStInputPassengerWorkFreeMapper, SwStInputPassengerWorkFree> implements SwStInputPassengerWorkFreeService {
    private final SwStInputPassengerWorkFreeMapper swStInputPassengerWorkFreeMapper;
    private final SwStInputPassengerWorkMapper swStInputPassengerWorkMapper;
    private final SwStmStationDataEntryLogService swStmStationDataEntryLogService;

    @Override
    public boolean saveInputWork(SwStInputPassengerWorkDTO<SwStInputPassengerWorkFree> workDTO) {
        //已提交的数据，在添加相同的数据就不能添加
        SwStInputPassengerWork passengerWorkOld = swStInputPassengerWorkMapper.selectOne(Wrappers.<SwStInputPassengerWork>query()
                .lambda().eq(SwStInputPassengerWork::getConductorCode, workDTO.getConductorCode())
                .eq(SwStInputPassengerWork::getWorkDate, workDTO.getWorkDate())
                .eq(SwStInputPassengerWork::getClassNumber, workDTO.getClassNumber())
                //.eq(SwStInputPassengerWork::getDeviceOperateNum, workDTO.getDeviceOperateNum())
                .eq(SwStInputPassengerWork::getSubmitStatus, "1")
                .eq(SwStInputPassengerWork::getDelFlag, "0")
                .eq(SwStInputPassengerWork::getInvalidStatus, "0")
        );
        if(ObjectUtil.isNotEmpty(passengerWorkOld) && passengerWorkOld != null){
            return false;
        }else {
            //此处查询的是未提交之前的添加
            SwStInputPassengerWork passengerWork = swStInputPassengerWorkMapper.selectOne(Wrappers.<SwStInputPassengerWork>query()
                            .lambda().eq(SwStInputPassengerWork::getConductorCode, workDTO.getConductorCode())
                            .eq(SwStInputPassengerWork::getWorkDate, workDTO.getWorkDate())
                            .eq(SwStInputPassengerWork::getClassNumber, workDTO.getClassNumber())
            );
            if(passengerWork == null){
                passengerWork = ObjectUtils.getDefaultObj(SwStInputPassengerWork.class);
                BeanUtils.copyProperties(workDTO, passengerWork, "workList");
				passengerWork.setBomCode(BeanUtilsStm.bomOrJobNoSort(passengerWork.getBomCode()));//bom编号排序后新增
                swStInputPassengerWorkMapper.insert(passengerWork);
            }
            final int relationId = passengerWork.getId();
            SwStInputPassengerWorkFree work = new SwStInputPassengerWorkFree();
            work.setRelationId(relationId);
            swStInputPassengerWorkFreeMapper.delete(Wrappers.query(work));
            workDTO.getWorkList().forEach(w -> {
                w.setRelationId(relationId);
                //重新计算合计
                //w.setTotal(Optional.ofNullable(w.getGateMisuseNumber()).orElse(0) + Optional.ofNullable(w.getMobileNoeleNumber()).orElse(0)
                //        + Optional.ofNullable(w.getTicketDamageNumber()).orElse(0) + Optional.ofNullable(w.getOtherNumber()).orElse(0));
            });
            this.saveBatch(workDTO.getWorkList());
            return true;
        }
    }

    @Override
    @Transactional
    public boolean updateInputWork(SwStInputPassengerWorkDTO<SwStInputPassengerWorkFree> workDTO) {
        SwStInputPassengerWork passengerWork = swStInputPassengerWorkMapper.selectOne(Wrappers
                .<SwStInputPassengerWork>query()
                .lambda().eq(SwStInputPassengerWork::getConductorCode, workDTO.getConductorCode())
                .eq(SwStInputPassengerWork::getWorkDate, workDTO.getWorkDate())
                .eq(SwStInputPassengerWork::getClassNumber, workDTO.getClassNumber()));
        final int relationId = passengerWork.getId();

        //修改之前添加记录表（先添加主表已经添加过的就不添加）
        if("1".equals(passengerWork.getReportModifyStatus())){
            SwStmStationDataEntryLog swStmStationDataEntryLogSelectOne = swStmStationDataEntryLogService.getBaseMapper()
                    .selectOne(Wrappers.<SwStmStationDataEntryLog>lambdaQuery()
                            .eq(SwStmStationDataEntryLog::getRelationId, relationId)
                            .eq(SwStmStationDataEntryLog::getLogTableName, StmTableCommon.SW_ST_INPUT_PASSENGER_WORK));
            List<SwStmStationDataEntryLog> list = new ArrayList<>();
            PigxUser user = SecurityUtils.getUser();
            if(swStmStationDataEntryLogSelectOne == null){
                passengerWork.setEntryUpdateJobNo(user.getUserCode());
                passengerWork.setEntryUpdateJobName(user.getNikeName());
                passengerWork.setEntryUpdateTime(new Date());
                SwStmStationDataEntryLog swStmStationDataEntryLog = new SwStmStationDataEntryLog();
                swStmStationDataEntryLog.setRelationId(passengerWork.getId());
                swStmStationDataEntryLog.setLogTableName(StmTableCommon.SW_ST_INPUT_PASSENGER_WORK);
                swStmStationDataEntryLog.setLogInfo(JSONObject.toJSONString(passengerWork));
                swStmStationDataEntryLog.setUpdateJobNo(user.getUserCode());
                swStmStationDataEntryLog.setUpdateJobName(user.getNikeName());
                swStmStationDataEntryLog.setUpdateTime(new Date());
                list.add(swStmStationDataEntryLog);
            }

            //修改之前添加记录表（再添加子表）
            List<SwStInputPassengerWorkFree> swStInputPassengerWorkFrees = swStInputPassengerWorkFreeMapper.selectList(
                    Wrappers.<SwStInputPassengerWorkFree>lambdaQuery()
                            .eq(SwStInputPassengerWorkFree::getRelationId, relationId)
                            //.eq(SwStInputPassengerWorkFree::getReportModifyStatus,"1")
            );

            if(CollectionUtil.isNotEmpty(swStInputPassengerWorkFrees)){
                swStInputPassengerWorkFrees.stream().forEach( workFree -> {
                    workFree.setEntryUpdateJobNo(user.getUserCode());
                    workFree.setEntryUpdateJobName(user.getNikeName());
                    workFree.setEntryUpdateTime(new Date());

                    SwStmStationDataEntryLog swStmStationDataEntryLogChild = new SwStmStationDataEntryLog();
                    swStmStationDataEntryLogChild.setRelationId(passengerWork.getId());
                    swStmStationDataEntryLogChild.setLogTableName(StmTableCommon.SW_ST_INPUT_PASSENGER_WORK_FREE);
                    swStmStationDataEntryLogChild.setLogInfo(JSONObject.toJSONString(workFree));
                    swStmStationDataEntryLogChild.setUpdateJobNo(user.getUserCode());
                    swStmStationDataEntryLogChild.setUpdateJobName(user.getNikeName());
                    swStmStationDataEntryLogChild.setUpdateTime(new Date());
                    list.add(swStmStationDataEntryLogChild);
                });
            }
            swStmStationDataEntryLogService.saveBatch(list);

        }
		/*
        if("1".equals(passengerWork.getReportModifyStatus())&&"1".equals(passengerWork.getIsMerge())){
            SwStInputPassengerWork newSwStInputPassengerWork = new SwStInputPassengerWork();
            newSwStInputPassengerWork.setId(passengerWork.getId());
            newSwStInputPassengerWork.setConfirmStatus("1");
            swStInputPassengerWorkMapper.updateById(newSwStInputPassengerWork);
        }*/
		//无论是否是报表修改状态，都要更新确认状态
		 SwStInputPassengerWork newSwStInputPassengerWork = new SwStInputPassengerWork();
         newSwStInputPassengerWork.setId(passengerWork.getId());
		 newSwStInputPassengerWork.setConfirmStatus("0");  
         if("1".equals(passengerWork.getReportModifyStatus())&&"1".equals(passengerWork.getIsMerge())){
		    newSwStInputPassengerWork.setConfirmStatus("1");
		 }		
         swStInputPassengerWorkMapper.updateById(newSwStInputPassengerWork);

        SwStInputPassengerWorkFree work = new SwStInputPassengerWorkFree();
        work.setRelationId(relationId);
        swStInputPassengerWorkFreeMapper.delete(Wrappers.query(work));//彻底删除
        workDTO.getWorkList().forEach(w -> {
            w.setRelationId(relationId);
            //重新计算合计
            //w.setTotal(Optional.ofNullable(w.getGateMisuseNumber()).orElse(0) + Optional.ofNullable(w.getMobileNoeleNumber()).orElse(0)
            //        + Optional.ofNullable(w.getTicketDamageNumber()).orElse(0) + Optional.ofNullable(w.getOtherNumber()).orElse(0));
        });
        return this.saveBatch(workDTO.getWorkList());
    }
}
